"use client"; //this is a client side component

import { registerGlobalSlice } from '@/pao/web';

import { getCounter, setCounter } from './service';

const initialState = {
  value: 0,
};

export const counterSlice = registerGlobalSlice({
  name: "counter",
  initialState,
  reducers: {
    setCount: (state, action) => {
      state.value = action.payload;
    },
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
}, {
  initialize: async (store) => {
    const counter = await getCounter();
    store.dispatch(counterSlice.actions.setCount(counter));
  },
  save: async (store) => {
    await setCounter(store.getState().counter.value);
  }
});

export const { setCount,increment, decrement, incrementByAmount } = counterSlice.actions;

export default counterSlice.reducer;

export const selectCounter = (state: any):number => state.counter.value;
